/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.backup;

import br.com.foxline.manager.ManagerReadFile;
import br.com.foxline.model.ActCep;
import br.com.foxline.model.Charter;
import br.com.foxline.model.City;
import br.com.foxline.model.Country;
import br.com.foxline.model.NatureWriting;
import br.com.foxline.model.Part;
import br.com.foxline.model.People;
import br.com.foxline.model.Quality;
import br.com.foxline.service.ActCepService;
import br.com.foxline.service.CharterService;
import br.com.foxline.service.CityService;
import br.com.foxline.service.CountryService;
import br.com.foxline.service.NatureWritingService;
import br.com.foxline.service.PartService;
import br.com.foxline.service.PeopleService;
import br.com.foxline.service.QualityService;
import br.com.foxline.util.Caracter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author ely
 */
@ManagedBean
@ViewScoped
public class ManagerNewReadFile {

    @EJB
    CityService cityService;
    @EJB
    CharterService charterService;
    @EJB
    CountryService countryService;
    @EJB
    ActCepService actCepService;
    @EJB
    NatureWritingService natureWritingService;
    @EJB
    PeopleService peopleService;
    @EJB
    QualityService qualityService;
    @EJB
    PartService partService;
    private Charter charter, charterSave;
    private Country country;
    private City city;
    private ActCep act, actCep;
    private NatureWriting natureWriting;
    private Part partOutorgado, partOutorgante;
    private People outorgado, oucpf, outcpf, oucnpj, outcnpj;
    private People outorgante;
    private List<ActCep> generatorsActs;
    private List<NatureWriting> generatorNatureWritings;
    private List<Part> parts, partsRemove;
    private Quality qualityOutorgado, qualityOutorgante;
    private UploadedFile file;

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    @PostConstruct
    public void init() {
        charter = new Charter();
        charterSave = new Charter();
        partOutorgado = new Part();
        partOutorgante = new Part();
        outorgado = new People();
        outorgante = new People();
        generatorsActs = new ArrayList<ActCep>();
        generatorNatureWritings = new ArrayList<NatureWriting>();
        parts = new ArrayList<Part>();
        partsRemove = new ArrayList<Part>();

    }

    public void read(InputStream arquivo) {
        String l = null;

        try {


            InputStreamReader reader = new InputStreamReader(arquivo);
            BufferedReader read = new BufferedReader(reader);

            StringTokenizer st = null;

            String liv;
            String fls;
            String esc;
            String out;
            String oud;
            String obj;
            String data;
            String tip;
            String cpfof;
            String cpfoj;
            String cpfdf;
            String cpfdj;
            String nullo;

            while ((l = read.readLine()) != null) {

                st = new StringTokenizer(l, ";");
                String dados = null;


                while (st.hasMoreTokens()) {

                    dados = st.nextToken();
                    liv = dados;

                    dados = st.nextToken();
                    fls = dados;

                    dados = st.nextToken();
                    esc = dados;

                    dados = st.nextToken();
                    out = dados;

                    dados = st.nextToken();
                    oud = dados;

                    dados = st.nextToken();
                    obj = dados;

                    dados = st.nextToken();
                    data = dados;

                    dados = st.nextToken();
                    tip = dados;

                    dados = st.nextToken();
                    cpfof = dados;

                    dados = st.nextToken();
                    cpfoj = dados;

                    dados = st.nextToken();
                    cpfdf = dados;

                    dados = st.nextToken();
                    cpfdj = dados;


                    String num = liv.replaceAll("\\D*", "");
                    String let = liv.replaceAll("\\d*", "");

                    String numF = fls.replaceAll("\\D*", "");
                    String letF = fls.replaceAll("\\d*", "");

 
                    charter.setBook(num);
                    charter.setBookComp(let);

                    charter.setLeaf(numF);
                    charter.setLeafComp(letF);

                    charter.setDateAct(converterData(data));

                    charter.setEsc(esc);

                    charter.setDescription(obj);

                    city = cityService.find(3493L);
                    charter.setCity(city);

                    country = countryService.find(18L);
                    charter.setUf(country);

                    actCep = actCepService.findActCod("1");


                    outorgante.setName(out);
                    outorgante.setCpf(Caracter.removecaracter(cpfof));
                    outorgante.setCnpj(Caracter.removecaracter(cpfoj));
                    qualityOutorgante = qualityService.findQualityCod("2");


                    outorgado.setName(oud);
                    outorgado.setCpf(Caracter.removecaracter(cpfdf));
                    outorgado.setCnpj(Caracter.removecaracter(cpfdj));
                    qualityOutorgado = qualityService.findQualityCod("1");

                    
                    // ESSE CÓDIGO ADICIONA NAS PARTES + AS PARTES ANTERIORES CONTINUAM
                    

                    // ADCIONANDO AS PARTES

//                    Charter c = charterService.existCharter(charter);
//                    if (c != null) {
//                        
//                        outorgante.setName(out);
//                        outorgante.setCpf(Caracter.removecaracter(cpfof));
//                        outorgante.setCnpj(Caracter.removecaracter(cpfoj));
//                        qualityOutorgante = qualityService.findQualityCod("2");
//                        
//                        outorgado.setName(oud);
//                        outorgado.setCpf(Caracter.removecaracter(cpfdf));
//                        outorgado.setCnpj(Caracter.removecaracter(cpfdj));
//                        qualityOutorgado = qualityService.findQualityCod("1");
//                         
//                        partOutorgante.setPeople(outorgante);
//                        partOutorgante.setPartQuality(qualityOutorgante);
//                        partOutorgado.setPeople(outorgado);
//                        partOutorgado.setPartQuality(qualityOutorgado);
//                        

//                        parts.add(partOutorgante);
//                        parts.add(partOutorgado);
//                        c.setParts(parts); 
//                        
//                        charterService.update(c);
//                        outorgado = new People();
//                        charter = new Charter();
//                        partOutorgado = new Part();
//                        outorgante = new People();
//                        partOutorgante = new Part();
//                        parts = new ArrayList<Part>();
//                        
//                    } else {
//                        System.out.println("NAO EXISTE");
//                    }
//                         


  // CRIA UMA PARTE E SUBSTITUI PELA ANTIGA OU SEJA A ANTIGA PASSA UMA NOVA PARTE
                    
                    Charter c = charterService.existCharter(charter);
                    if (c != null) {
                        partsRemove = partService.getPartsByCharter(c);
                        for (Part parte : partsRemove) {
                            if (parte.getPartQuality().getCod().equals("2")) {
                                parte.setPeople(outorgante);
                            }
                            if (parte.getPartQuality().getCod().equals("1")) {
                                parte.setPeople(outorgado);  
                            }
                            parts.add(parte); 
                        }  
                        c.setParts(parts);
                        charterService.update(c);
                        outorgado = new People();
                        charter = new Charter();
                        partOutorgado = new Part();
                        outorgante = new People();
                        partOutorgante = new Part();
                        parts = new ArrayList<Part>();


                    }



                }
            }
            read.close();
            reader.close();

        } catch (Exception erro) {
            erro.printStackTrace();
            System.err.println(erro);
        }

    }

    public Date converterData(String data) {
        if (data == null || data.equals("") || data.equals(".")) {
            return null;
        }

        Date date = null;
        try {
            DateFormat formater = new SimpleDateFormat("dd/MM/yyyy");
            date = (Date) formater.parse(data);

        } catch (ParseException ex) {
            Logger.getLogger(ManagerNewReadFile.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
        return date;
    }

    public void upload() throws IOException {
        String namefile = "";


        if (file != null) {
            namefile = file.getFileName();
        }


        FacesContext facesContext = FacesContext.getCurrentInstance();
        ServletContext scontext = (ServletContext) facesContext.getExternalContext().getContext();

        String caminho = scontext.getRealPath("" + namefile);

        caminho = "/opt/glassfish3/glassfish/";

        System.out.println("caminho " + caminho);
        if (file != null) {
            read(file.getInputstream());
        }


    }
}
